var $ = require('jquery');
var message = require('../message');
var notice = require('../notice');

var $listTmp = $('<div class="im-chat-list">');
module.exports.create = function ($parent) {
  var $list = $listTmp.clone();
  $parent.append($list);
  return new List($list);
};

function List($list) {
  this.$list = $list;
  this.length = 0;
}

/**
 * 添加消息到消息列表
 * @param {Boolean} isSelf 是否为自己发送的消息
 * @param {Object} msg
 */
List.prototype.appendMsg = function (isSelf, msg) {
  console.log('append----------------------');
  var $list = this.$list;
  if (msg.msgId && $list.find('#msg-' + msg.msgId).length) {
    return;
  }
  var $msg = message.create(isSelf, msg);
  if (!$msg) {
    return;
  }
  $list.append($msg);
  this.length++;
  this.scrollToBottom();
};


List.prototype.appendNotice = function (content, url, type) {
  console.log('append notice', content, url, type);
  var $notice = notice.create(content, url, type);
  var $list = this.$list;
  $list.append($notice);
  this.scrollToBottom();
};

List.prototype.scrollToBottom = function () {
  var $list = this.$list;
  //var totalHeight = 0;
  //$list.children().each(function (index, ele) {
  //  totalHeight += $(ele).height();
  //});
  var list = document.getElementById('chat-' + window.Meta.chatId).childNodes[0].childNodes[0];
  // var scrollVal = list.scrollHeight - list.offsetHeight;
  // $list.animate({scrollTop: scrollVal}, 300);
};
